package com.metacube.metaconnect.controller;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.metacube.metaconnect.Service.UserInformationService;
import com.metacube.metaconnect.model.ActivationForm;
import com.metacube.metaconnect.model.GenerateActivationLink;

public class ActivationAction extends Action {

	/*
	 * send the activation mail to user on sign-up
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ActivationForm activation_form = (ActivationForm) form;

		// email_id provided by user
		String emailId = activation_form.getEmail() + "@"
				+ activation_form.getDomains();

		try {
			// checking whether user already have a account
			boolean result = new UserInformationService()
					.alreadyActivate(emailId);

			if (result) {
				request.setAttribute("signupError", "active");
			}

			else {
				GenerateActivationLink objGenerateActivationLink = new GenerateActivationLink();
				String activationLink = objGenerateActivationLink
						.generateActivationLink();

				String activationCodeString = activationLink
						.substring(activationLink.indexOf("=") + 1);

				if (activationCodeString == null) {
					request.setAttribute("signupError", "wrong");
				} else {
					int activationCode = Integer.parseInt(activationCodeString);

					new UserInformationService().insertInactiveUserDetails(
							emailId, activationCode);

					SendEmail objSendEmail = new SendEmail();

					String bodyText = "Welcome to MetaConnect family, click the link below to activate your account\n\n\n"
							+ activationLink
							+ "\n\n Thanks And Regards \nTeam MetaConnect";

					// send mail to user containing activation link
					objSendEmail.sendMail(emailId,
							"MetaConnect Activation Link", bodyText);

					request.setAttribute("signupError", "false");
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			request.setAttribute("signupError", "incorrect");
		}
		return mapping.findForward("success");

	}
}
